package com.acane.instagram.feature.search

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class SearchViewModel(

): ViewModel() {

    private var _refresh = MutableStateFlow<Boolean>(false)
    val refresh = _refresh
    fun startRefresh() {
        viewModelScope.launch {
            _refresh.value = true
            delay(1000)
            _refresh.value = false

        }
    }

    var caption by mutableStateOf("")

    fun updateCaption(newValue: String) {
        caption = newValue
    }

    private val _userSearchResults = MutableStateFlow<List<UserInfo>?>(emptyList()) // 初始值为空列表
    val userSearchResults: StateFlow<List<UserInfo>?> = _userSearchResults // 用于暴露给外部使用

    private val _postSearchResults = MutableStateFlow<List<PostInfo>?>(emptyList()) // 初始值为空列表
    val postSearchResults: StateFlow<List<PostInfo>?> = _postSearchResults // 用于暴露给外部使用

    private val _loading = MutableStateFlow(false) // 加载状态
    val loading: StateFlow<Boolean> = _loading // 用于暴露给外部使用

    // 发起网络请求获取搜索结果
    fun search(query: String) {
        if (query.isEmpty()) {
            _userSearchResults.value = emptyList() // 输入为空时返回空列表
            return
        }

        _loading.value = true

        // 使用协程进行异步请求
        viewModelScope.launch {
            try {
                val userResponse = MyRetrofitDatasource.userSearchResults(query)
                val postResponse = MyRetrofitDatasource.postSearchResults(query)
                // 填充两个搜索结果
                _userSearchResults.value = userResponse.data
                _postSearchResults.value = postResponse.data

            } catch (e: Exception) {
                _userSearchResults.value = emptyList() // 发生错误时返回空列表
                _postSearchResults.value = emptyList()
            } finally {
                _loading.value = false // 请求结束，关闭加载状态
            }
        }
    }

    fun getPostPosition(postId: String): Int {
        if (postSearchResults.value != null) {
            return postSearchResults.value!!.indexOfFirst { it.id == postId }
        }
        return 0
    }

}
//@Serializable
//data class SearchResultData<T> (
//    val type: String,
//    val data: T
//)
